from promisecheck.models import Promise, Status, Log, DateStats
from openpolitics.models import Person
from django.utils.datastructures import SortedDict

import datetime

def promises_list(person):
    statuses = Status.objects.all()    
    promises = person.promises.all()
    l = {}
    if not len(statuses):
        return l
    for i in statuses:
        l[i.name] = 0
    for p in promises:
        for i in statuses:
            if i==p.status:
                l[i.name] += 1
    l['suma'] = promises.count()
    return l

def update_promise_status(log):
    log.promise.status=log.status
    log.promise.save()

def _add_day(l,i):
    for k,v in i.items():
        l[k-1]+=v

def _change_or_create(d, day, status, v):
    if not day in d:
        d[day] = {}
    if not status in d[day]:
        d[day][status] = v
    else:
        d[day][status] += v

def rebuild_datestats(pid=10):
    
    DateStats.objects.all().delete()
    
    person = Person.objects.get(id=pid)
    
    statuses = Status.objects.all()
    
    delta = SortedDict()
    promises = Promise.objects.filter(person=person).order_by('date', 'id')

    for promise in promises:
        day = promise.date.strftime("%Y.%m.%d")
        status = 1 
        _change_or_create(delta, day, status, 1)
        for log in promise.logs.all():
            lday = log.date.strftime("%Y.%m.%d")
            lstatus = log.status.pk
            _change_or_create(delta, lday, status, -1)
            _change_or_create(delta, lday, lstatus, 1)
            status = lstatus

    aggregate = [0]*len(statuses)
    fstr = delta.keys()[0]
    first = datetime.date(int(fstr[0:4]),
                          int(fstr[5:7]),
                          int(fstr[8:10]))
    lstr = delta.keys()[-1]
    last = datetime.date(int(lstr[0:4]),
                          int(lstr[5:7]),
                          int(lstr[8:10]))
    for i in range(0,(last-first).days+1):
        day = (first+datetime.timedelta(i)).strftime("%Y.%m.%d")
        if day in delta:
            _add_day(aggregate, delta[day])
        for k,v in enumerate(aggregate):
            ds = DateStats(person=person,
                           date=first+datetime.timedelta(i),
                           status_id=(k+1),
                           value = v)
            ds.save()
        print '%s: %s' % (day, aggregate)

            
        